package org.qufenqi.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.qufenqi.api.common.CommonResponse;
import org.qufenqi.api.common.ConstantPropertiesUtils;
import org.qufenqi.api.entity.Account;
import org.qufenqi.api.entity.Item;
import org.qufenqi.api.mapper.AccountMapper;
import org.qufenqi.api.mapper.ItemMapper;
import org.qufenqi.api.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.concurrent.TimeUnit;

@Service("fileService")
public class FileServiceImpl implements FileService {
    private String endpoint = ConstantPropertiesUtils.ENDPOINT;
    private String accessKeyId = ConstantPropertiesUtils.KEYID;
    private String accessKeySecret = ConstantPropertiesUtils.KEYSECRET;
    private String bucketName = ConstantPropertiesUtils.BUCKETNAME;


    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    public CommonResponse<Object> UploadUserPicture(int userId,MultipartFile file){
        //获取上传文件名称
        String filename = file.getOriginalFilename();
        System.out.println("上传文件名称：" + filename);

        assert filename != null;
        filename = userId + filename.substring(filename.lastIndexOf("."));

        //阿里云上的文件路径
        String path = "http://" + bucketName + "." + endpoint + "/user/" + filename;
        try {

            InputStream inputStream = file.getInputStream();
            /*上传过程*/
            // 创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);

            //上传文件流。 参数分别为仓库名称，文件名称，文件流
            ossClient.putObject(bucketName,"user/" + filename,inputStream);

            //关闭OSSClient
            ossClient.shutdown();

        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.responseForErrorMessage("上传失败");
        }

        Account account = new Account();
        account.setUserId(userId);
        account.setDescn(path);
        accountMapper.updateById(account);
        account = accountMapper.selectById(userId);

        String redisKey = account.getUsername()+"Info";

        //redis序列化
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);

        try {
            redisTemplate.delete(redisKey);
        }
        catch (Exception ex){
            System.out.println("无缓存，不需要删除");
        }


        return CommonResponse.responseForSuccessMessage("上传成功，路径为：" + path);
    }


    //获取用户照片链接
    public CommonResponse<String> GetUserPicture(int userId,String userName){

        String name = userName;

        //redis字符串序列化器
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);

        //查询缓存
        String jsonList = JSON.toJSONString(redisTemplate.opsForValue().get(name + "Info"));
        Account userinfo = JSON.parseObject(jsonList,Account.class);

        if(userinfo == null){
            System.out.println("从数据库中获取数据");
            //缓存为空，查询一遍数据库
            userinfo = accountMapper.selectById(userId);
            //把获得数据放入redis
            redisTemplate.opsForValue().set(name + "Info",userinfo,3L, TimeUnit.DAYS);
        }
        else {
            System.out.println("直接从缓存中获取数据");
        }

        if(userinfo.getDescn().equals("")){
            return CommonResponse.responseForErrorMessage("用户未上传头像");
        }
        return CommonResponse.responseForSuccessMessage(userinfo.getDescn());
    }





    //item
    @Override
    public CommonResponse<String> itemPictureUpload(String itemsort,String productid,MultipartFile file){

        Item item = new Item();
        item.setItemSort(itemsort);
        item.setProductId(productid);

        //获取上传文件名称
        String filename = file.getOriginalFilename();
        System.out.println("上传文件名称：" + filename);

        item.setItemName(filename.substring(0,filename.length()-4));
        item.setDesc1(filename);

        //阿里云上的文件路径
        String path = "http://" + bucketName + "." + endpoint + "/item/" + filename;
        try {

            InputStream inputStream = file.getInputStream();
            /*上传过程*/
            // 创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);

            //上传文件流。 参数分别为仓库名称，文件名称，文件流
            ossClient.putObject(bucketName,"item/" + filename,inputStream);

            //关闭OSSClient
            ossClient.shutdown();

        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.responseForErrorMessage("上传失败");
        }


        item.setImage(path);
        itemMapper.insert(item);


        return CommonResponse.responseForSuccess("成功");
    }
}
